#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# shellcheck disable=SC1091
source cki_utils.sh

ARCHITECTURES=(aarch64 ppc64le s390x x86_64)
KERNELS_DIR=/tmp/kernels

# shellcheck disable=SC2154
cki_parse_bucket_spec "${BUCKET_CONFIG_NAME}"
# shellcheck disable=SC2154
AWS_S3="aws s3 --endpoint ${AWS_ENDPOINT}"
# shellcheck disable=SC2154
S3_PATH="s3://${AWS_BUCKET}/${AWS_BUCKET_PATH}"

for ARCH in "${ARCHITECTURES[@]}"; do
    mkdir -vp "${KERNELS_DIR}/${ARCH}"
    pushd "${KERNELS_DIR}/${ARCH}"
        cki_echo_yellow "Downloading kernel and extracting config for ${ARCH}"

        # Use rawhide kernel configs as they are the closest to the mainline kernels.
        baseurl=$(curl \
            ${CKI_CURL_CONFIG_FILE+--config "${CKI_CURL_CONFIG_FILE}"} \
            "https://mirrors.fedoraproject.org/mirrorlist?repo=rawhide&country=global&arch=${ARCH}" | \
            grep -m 1 dl.fedoraproject.org)
        dnf download \
            --assumeyes \
            --repo adhoc-rawhide \
            --repofrompath "adhoc-rawhide,${baseurl}" \
            --forcearch "${ARCH}" \
            --destdir . \
            kernel-core
        rpm2cpio kernel-core-*."${ARCH}".rpm | cpio -idmB
        cp lib/modules/*/config "${KERNELS_DIR}/${ARCH}.config"
    popd
done
cki_echo_green "Configs successfully extracted"

cki_echo_yellow "Uploading configs to ${S3_PATH}"
for configfile in "${KERNELS_DIR}"/*.config ; do
    ${AWS_S3} cp --no-progress "${configfile}" "${S3_PATH}$(basename "${configfile}")"
done

cki_echo_green "Configs successfully updated"
